package com.zzyl.framework.interceptor;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.SecurityUtils;
import com.zzyl.common.utils.UserThreadLocal;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Autowired
    private HttpServletRequest request;

    @SneakyThrows
    public boolean isExclude() {
        try {
            String requestURI = request.getRequestURI();
            log.info("Request URI: {}", requestURI);
            if(requestURI.startsWith("/member")) {
                return true;
            }
            return false;
        } catch (Exception e) {
            return true;
        }
    }

    // 插入数据时自动填充
    @Override
    public void insertFill(MetaObject metaObject) {
        if(!isExclude()) {
            this.strictInsertFill(metaObject, "createBy", String.class, String.valueOf(getLoginUserId()));
        } else {
            this.strictInsertFill(metaObject, "createBy", String.class, String.valueOf(getMiniProgramUserId()));
        }
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
    }

    // 修改数据时自动填充
    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime", new Date(), metaObject);
        if(!isExclude()) {
            this.setFieldValByName("updateBy", getLoginUserId() + "", metaObject);
        } else {
            this.setFieldValByName("updateBy", String.valueOf(getMiniProgramUserId()), metaObject);
        }

    }

    // 获取当前登录人的id
    public Long getLoginUserId() {
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (ObjectUtils.isNotEmpty(loginUser)) {
                return loginUser.getUserId();
            }
        } catch (Exception e) {
            log.warn("获取用户信息异常，使用默认用户ID: 1L", e);
        }
        return 1L;
    }

    // 获取微信小程序端的用户ID
    public Long getMiniProgramUserId() {
        try {
            Long userId = UserThreadLocal.getUserId();
            if (ObjectUtils.isNotEmpty(userId)) {
                return userId;
            }
        } catch (Exception e) {
            log.warn("获取用户信息异常，使用默认用户ID: 2L", e);
        }
        return 2L;
    }
}